﻿// cac ham xu ly thong tin
var arrDivInclude       = ['divArticleMess','divArticleFillter','AddEditForm'];
var recordsPerPage = 15;//$('#slcPerPage').val();
var totalRows = 0;
var flag;
var isacrId;
var createDate;
pageCurrent =1;
var cachePageSet =0;
var title="",state="",viewid=0, authorF="",fromdate ="", todate ="";

//init data
function LoadAllArticles(){
    LoadGrid(title,state,viewid,authorF,fromdate,todate,recordsPerPage,1);
}

/*---------------------------Luoi hien thi du lieu-----------------------------------------*/
function LoadGrid(title,state,viewid,authorF,fromdate,todate,recordsPerPage,pageCurrent)
{
    HAAT.Web.Cmsadmin.Modules.ArticleInfo.CountRecordbyFilter(title, state, viewid, authorF, fromdate, todate, channelId, function(respone){        
        if(respone.value==null || respone.value ==0){
           $("#trNoData").attr('style','display:');
           $("#pattern_Id").attr('style', 'display:none');
           $("#Is_Paging").attr('style','display:none');
                    util.removeAllRows('show_Grid', { filter:function(tr) {
                       return(tr.id != "pattern_Id");
                    }});
       }else{
            $("#trNoData").attr('style','display:none');
            totalRows = respone.value;
            HAAT.Web.Cmsadmin.Modules.ArticleInfo.GetAllArticle(title, state, viewid, authorF, fromdate, todate, recordsPerPage, 
                pageCurrent, channelId, function(respone){
                    if(respone.value!=null)
                    {
                        $("#pattern_Id").attr('style', 'display:none');
                            util.removeAllRows('show_Grid', { filter:function(tr) {
                            return(tr.id != "pattern_Id");
                        }});
                        var cid,listObj; 
                        if(respone.value!=null){
                           var iList = respone.value;  
                           for(i=0;i< iList.length ; i++)
                           { 
                             listObj = iList[i];
                             cid = listObj.Id;
                             css = (i%2== 0)?'Row_Odd':'Row_Round';
                             util.cloneNode('pattern_Id', {idSuffix:cid });                     
                             link = "<a href=\"Modules/ArticleDetail.aspx?contentid=" + cid + "&TB_iframe=true&height=500&width=500&inlineId=myOnPageContent\" class=\"thickbox\" title=\"Xem chi tiet\">" + iList[i].Title+ "</a>";
                             $("#titleId"+ cid).html(link);
                             $("#updateId"+ cid).html(util.convertDateVN(iList[i].Updatedon));
                             $("#stateId"+ cid).html((iList[i].State==false)?"Chưa duyệt":"Duyệt");
                             $('#pattern_Id'+cid).attr('style', 'display:');
                             $('#pattern_Id'+cid).attr('class', css);
                           }
                           tb_init('a.thickbox'); 
                        }
                    }		
                    pt =callPage(pageCurrent,cachePageSet,totalRows,recordsPerPage,"gotoPageArticle");
                    $("#Is_Paging").attr('style','display:');
                    $("#Is_Paging").html(pt);
                });
            } 
        });
}


/*---------Hien thi hop loc----------------------------------------------------------------------*/
function showFilter(){

    var div = $("#divArticleFillter");
    if (div.attr('class') == "panelHidden"){
        SHObjectAll("divArticleFillter");        
        $("#aExpand").attr('style','display:none');
        $("#aCollape").attr('style','display:');      
        BindViewCombo("slView"); 
    }else{
        SHObjectAll("div_ViewArticle");
        $("#aExpand").attr('style','display:');
        $("#aCollape").attr('style','display:none');
    }
    return false;
}
/*-----------------Loc du lieu-----------------------------------------------------------------*/
function Filter_Click()
{
    title =$('#txtTitle_F').val();
    state =$('#slState').val();
    viewid =$('#slView').val();
    authorF =$('#txtAuthorF').val();
    todate =$('#txtToDate').val();
    fromdate =$('#txtFromDate').val();
    LoadGrid(title,state,viewid,authorF,fromdate,todate,recordsPerPage,pageCurrent);
    
}
/*-----------------Mac dinh-----------------------------------------------------------------*/
function Default_Click()
{
    title ="";
    state ="";
    viewid =0;
    authorF="";
    fromdate="";
    todate ="";
    $('#authorF').val('');
    $('#txtToDate').val('');
    $('#txtFromDate').val('');
    $('#slState').val('');
    $('#slView').val(0);
    LoadGrid(title,state,viewid,authorF,fromdate,todate,recordsPerPage,pageCurrent);
}

//----------------------------------------------------------------------------------------------------------------
//Goi phan trang
//----------------------------------------------------------------------------------------------------------------
function gotoPageArticle(pageCurrent, base) {  
    LoadGrid(title,state,viewid,authorF,fromdate,todate,recordsPerPage ,pageCurrent);
    pt =callPage(pageCurrent,cachePageSet,totalRows,recordsPerPage,"gotoPageArticle");
    $("#Is_Paging").attr('style','display:');
    $("#Is_Paging").html(pt);
}
function ChangePage()
{
    recordsPerPage = $('#slcPerPage').val();
    LoadGrid(title,state,viewid,authorF,fromdate,todate,recordsPerPage ,pageCurrent);
}
function BindViewCombo(combox, val){   
    var myOption = $("#" + combox);  
    var pos = true;  
    HAAT.Web.Cmsadmin.Modules.ArticleInfo.GetViewbyLangid(channelId, function(drpcombox){       
        drpCombox = drpcombox.value;
        // Clear the <select> of existing options
        myOption.empty();
        if (drpCombox.length != 0) {
            $.each(drpCombox, function() {
                if (pos) {
                    pos = false;
                    myOption.append(
                       $('<option></option').val(0).html("--Chọn tất cả--")
                    );
                    myOption.append(
                       $('<option></option').val(this.Id).html(this.Name)
                    );
                }else{
                    myOption.append(
                       $('<option></option').val(this.Id).html(this.Name)
                    );
               }
            });            
        }
        if (val!=null){
            myOption.val(val); 
        }        
    });   
}
function SelectAllCheckboxes(spanChk){
    var oItem = spanChk.children;
    var theBox= (spanChk.type=="checkbox") ? 
    spanChk : spanChk.children.item[0];
    xState=theBox.checked;
    elm=theBox.form.elements;
    for(i=0;i<elm.length;i++){
        if(elm[i].type=="checkbox" && elm[i].id!=theBox.id) {
            if(elm[i].checked!=xState)
            elm[i].click();
        }
    }
}
function addArticle()
{
    btnReset_Click();
    SHObjectAll("AddEditForm");
    BindViewCombo("slTypeArticle");
    flag = "ADD";
} 
function showFormEditNote(element)
{
    var acrId = element.substring(4);
    isacrId = acrId;
    flag = "EDIT";
    btnReset_Click();
    SHObjectAll("AddEditForm");    
    HAAT.Web.Cmsadmin.Modules.ArticleInfo.GetEditById(acrId, function (entity){
        var oArt = entity.value;
        createDate = util.convertDateVN(oArt.Createdon);
        BindViewCombo("slTypeArticle",oArt.Viewid);
        $('#txtTitle').val(oArt.Title);
        $('#txtSummary').val(oArt.Summary);
        $("#txtAttach").val(oArt.Pathfile);  
        $('#txtImage').val(oArt.Pathimage);
        $('#txtAuthor').val(oArt.Author);
        $('#chkNew').attr("checked",oArt.Isnew);
        $('#chked').attr("checked",oArt.State);
        $('#txtDate').val(util.convertDateVN(oArt.Poston));
        $('#txtNoteImage').val(oArt.Imgdesc);
        InsertTextFCK(txtContent,oArt.Content);
    });
}
function btnOK_Click()
{  
     if(validata()){
       var entity;
       $('#chkState')[0].checked
        var isNewCheck = $('#chkNew')[0].checked;//document.getElementById('chkNew').checked;
        var isStateCheck = $('#chked')[0].checked;// =document.getElementById('chked').checked;
        strDate = $('#txtDate').val().split('/');
        year = parseInt(strDate[2]);
        while(strDate[1].substr(0,1)=='0' && strDate[1].length>1) strDate[1] = strDate[1].substr(1);
        month = parseInt(strDate[1]);
        while(strDate[0].substr(0,1)=='0' && strDate[0].length>1) strDate[0] = strDate[0].substr(1);
        day = parseInt(strDate[0]);
        strDate = new Date(year,month-1,day);
        //Lay ngay cap nhat hien tai
        CTempDate =currentDate;
        CDate = CTempDate.split('/');
        while(CDate[1].substr(0,1)=='0' && CDate[1].length>1) CDate[1] = CDate[1].substr(1);
        month = parseInt(CDate[1]);
        while(CDate[0].substr(0,1)=='0' && CDate[0].length>1) CDate[0] = CDate[0].substr(1);
        day = parseInt(CDate[0]);
        CDate = new Date(year,month-1,day);
        
       if(flag=="ADD")
       {    
           entity ={
                Id :-1,
                Viewid: $('#slTypeArticle').val(),
                Title :$('#txtTitle').val(),
                Summary: $('#txtSummary').val(),
                Content :getTextFCK(txtContent),
                Pathfile:$('#txtAttach').val(),
                Pathimage:$('#txtImage').val(),
                Updatedon:strDate,
                Createdon:strDate,
                Langid:1,
                Author:$('#txtAuthor').val(),
                Isnew:isNewCheck,
                State:isStateCheck,
                Poston:strDate,
                Imgdesc:$('#txtNoteImage').val()
          };
          HAAT.Web.Cmsadmin.Modules.ArticleInfo.AddNewArticles(entity,function(result){
            if(result.value)
            {
                ShowMessage("divArticleMess","tdMessage", "Bạn đã thêm mới thành công!");
            }
            else
            {
                ShowMessage("divArticleMess","tdMessage", "Thêm mới không thành công!");
            }
          });
       }
       if(flag =="EDIT")
       {
            //Lay ngay tao 
            crDate = createDate.split('/');
            while(crDate[1].substr(0,1)=='0' && crDate[1].length>1) crDate[1] = crDate[1].substr(1);
            month = parseInt(crDate[1]);
            while(crDate[0].substr(0,1)=='0' && crDate[0].length>1) crDate[0] = crDate[0].substr(1);
            day = parseInt(crDate[0]);
            crDate = new Date(year,month-1,day);
            entity ={
                Id :isacrId,
                Viewid: $('#slTypeArticle').val(),
                Title :$('#txtTitle').val(),
                Summary: $('#txtSummary').val(),
                Content :getTextFCK(txtContent),
                Pathfile:$('#txtAttach').val(),
                Pathimage:$('#txtImage').val(),
                Updatedon:CDate,
                Createdon:crDate,
                Langid:1,
                Author:$('#txtAuthor').val(),
                Isnew:isNewCheck,
                State:isStateCheck,
                Poston:strDate,
                Imgdesc:$('#txtNoteImage').val()
            };
           HAAT.Web.Cmsadmin.Modules.ArticleInfo.UpdateArticles(entity,function(result){
                if(result.value)
                {
                    ShowMessage("divArticleMess","tdMessage", "Bạn đã hiệu chỉnh thành công!");
                }
                else
                {
                    ShowMessage("divArticleMess","tdMessage", "Hiệu chỉnh không thành công!");
                }
           });
       }
       LoadGrid(title,state,viewid,authorF,fromdate,todate,recordsPerPage,1);       
     }
}

//btnReset_Click 
function  btnReset_Click()
{
   // var content =' ';
    $('#slTypeArticle').val(0);
    $('#txtTitle').val('');
    $('#txtDate').val(currentDate);
    $('#txtAttach').val('');
    $('#txtImage').val('');
    $('#txtAuthor').val('');
    $('#txtNoteImage').val('');
    $('#txtSummary').val('');
    $('#chkNew').attr("checked",false);
    $('#chked').attr("checked",false);
    InsertTextFCK(txtContent,content);
   //var oEditor = FCKeditorAPI.GetInstance(txtContent) ;
   // return oEditor.SetHTML("");   
}
function  Close_Click()
{
    HiddenPanel("AddEditForm");
}
//DeleteArticles
function deleteArticle()
{
    var listIDs = getChecked("chkBox",6);
    if(listIDs==""){
        alert(msgNocheck);
        return false;
    }   
   if(confirm(msgConfirm)){
        $("chkAllBox").checked = false;
        HAAT.Web.Cmsadmin.Modules.ArticleInfo.DeleteArticles(listIDs, function(result){
            if(result.value)
            {
                ShowMessage("divArticleMess","tdMessage", msgDel);        
                LoadGrid(title,state,viewid,authorF,fromdate,todate,recordsPerPage,1);      
            }
            else
            {
                ShowMessage("divArticleMess","tdMessage", msgDelErr);        
            }
        });
        return true; 
   }else {
        return false;
   }        
}
function approveArticle()
{
    var catUpStateId='';
    var allchk = document.getElementById("tblViewActicle").getElementsByTagName("input");
    for (i=1; i< allchk.length-4; i++)
    {
        if((allchk.item(i).type=='checkbox')&& (allchk.item(i).name=='chkBox'))
        {
            if(allchk.item(i).checked==true)
            {
                if(catUpStateId=='')
                    catUpStateId = allchk.item(i).id.substring(6);
                else
                    catUpStateId = catUpStateId + "," +allchk.item(i).id.substring(6);
            }
        }
    }
    if(catUpStateId==0)
    {
        alert("Vui lòng chọn mẫu tin");
        return false;
    }
    if(confirm("Bạn chắc chắn muốn thay đổi trạng thái")){
        $("chkAllBox").checked = false;
        HAAT.Web.Cmsadmin.Modules.ArticleInfo.UpdateStateArt(catUpStateId,function(result){
            if(result.value){
                ShowMessage("divArticleMess","tdMessage", "Cập nhật trạng thái thành công!");        
                LoadGrid(title,state,viewid,authorF,fromdate,todate,recordsPerPage,1);
            }else{
                ShowMessage("divArticleMess","tdMessage", "Cập nhật trạng thái không thành công!");
            }
        });
        
        return true; 
    }else{
        return false;
    }
}
function validata()
{
    var title = $('#txtTitle');
    var type =$('#slTypeArticle');
    var date = $('#txtDate');
    if(title.val()=="")
    {
        alert("Vui lòng nhập tiêu đề!");
        title.focus();
        return false;
    }
    if(type.val()==0)
    {
        alert("Vui lòng chọn thể loại!");
        type.focus();
        return false;
    }
    if(date.val()== "")
    {
        alert("Vui lòng chọn ngày tháng!");
        date.focus();
        return false;
    }
    else
    {
        if(!isDate_ddmmyyyy(date.val()))
        {
            alert("Ngày nhập vào không hợp lệ!");
            date.focus();
            return false;
        }
    }
    return true;
}